/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets;

import dao.ClienteDAO;
import entity.Cliente;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Paulinha
 */
@WebServlet(name = "ControladoraCliente", urlPatterns = {"/ControladoraCliente"})
public class ControladoraCliente extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException, ParseException {

        String action = request.getParameter("action");

        if (action.equals("inserir")) {
            
            SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
            
            String nome = request.getParameter("nome");
            String cpf = request.getParameter("campoCpf");
            Date dt_nasc = new Date(df.parse(request.getParameter("dt_nasc")).getTime());
            String sexo = request.getParameter("sexo");            
            String endereco = request.getParameter("endereco");
            String email = request.getParameter("email");

            Cliente cliente = new Cliente();
            cliente.setNome(nome);
            cliente.setCpf(cpf);
            cliente.setDt_nasc(dt_nasc);
            cliente.setSexo(sexo);
            cliente.setEndereco(endereco);
            cliente.setEmail(email);

            ClienteDAO dao = new ClienteDAO();

            if (dao.cpfExistente(cpf)){
                
            request.setAttribute("mensagemcpf","Cpf já cadastrado");  
            RequestDispatcher rd = request.getRequestDispatcher("/cadastra_cliente.jsp");
            rd.forward(request, response);    
                
            }
                
            dao.insere(cliente);

            RequestDispatcher rd = getServletContext().getRequestDispatcher("/buscar_cliente.jsp");
            rd.forward(request, response);
            
        } else if (action.equals("alterar")) {
            
            SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
            
            String id = request.getParameter("id");
            String nome = request.getParameter("nome");
            Date dt_nasc = new Date(df.parse(request.getParameter("dt_nasc")).getTime());
            String endereco = request.getParameter("endereco");
            String email = request.getParameter("email");
            
            int num = 0;
            num = Integer.parseInt(id); 
            Cliente cliente = new Cliente();
            cliente.setIdCliente(num);
            cliente.setNome(nome);
            cliente.setDt_nasc(dt_nasc);
            cliente.setEndereco(endereco);
            cliente.setEmail(email);
            ClienteDAO dao = new ClienteDAO();
            dao.altera(cliente);
            RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/buscar_cliente.jsp");
            rd.forward(request, response);            
            
        } 
        else if (action.equals("deletar")){

        int iduser = Integer.parseInt(request.getParameter("id"));
       
        Cliente cliente = new Cliente();
        cliente.setIdCliente(iduser);
            
        ClienteDAO dao = new ClienteDAO();
        dao.excluir(cliente);
        
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/buscar_cliente.jsp");
        rd.forward(request, response);
        }
        
        else if (action.equals("visualizar")) {

            String id = request.getParameter("id");
            int num = 0;
            num = Integer.parseInt(id);
            Cliente cliente = new Cliente();
            ClienteDAO dao = new ClienteDAO();
            cliente = dao.buscaCli(num);
            request.setAttribute("cliente", cliente);
            RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/detalhes_cliente.jsp");
            rd.forward(request, response);   
            
        }
        
        else if (action.equals("mostrar")) {
            
            String id = request.getParameter("id");
            int num = 0;
            num = Integer.parseInt(id);
            Cliente cliente = new Cliente();
            ClienteDAO dao = new ClienteDAO();
            cliente = dao.buscaCli(num);
            request.setAttribute("cliente", cliente);
            RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/cliente_altera.jsp");
            rd.forward(request, response);  
            
        }  else if (action.equals("pesquisar")){            
            String pesquisa = request.getParameter("busca_cliente");                                          
            ClienteDAO daocliente = new ClienteDAO();
            List<Cliente> cliente = daocliente.procurar(pesquisa);            
            request.setAttribute("cliente", cliente);
            RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/buscar_cliente_listados.jsp");
            rd.forward(request, response);
        } else {
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/buscar_cliente.jsp");
            rd.forward(request, response);
        }

    }

 // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(ControladoraCliente.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(ControladoraCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(ControladoraCliente.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(ControladoraCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
